package com.xiaolei.lib.annotation.factory;

import java.util.LinkedHashMap;

/**
 * 对全局所有的Bean进行缓存，并且单例
 * @author xiaolei
 */
public class BeanFactory extends LinkedHashMap<Object, Object>
{
	private static final long serialVersionUID = 8225281633825636800L;
	private static BeanFactory factory;
	public static <T> T getInstance(Class<T> key)
	{
		synchronized (BeanFactory.class)
		{
			if(factory == null)
			{
				synchronized (BeanFactory.class)
				{
					factory = new BeanFactory();
				}
			}
		}
		
		@SuppressWarnings("unchecked")
		T result =  (T) factory.get(key);
		if(result == null)
		{
			try
			{
				result = key.newInstance();
				factory.put(key, result);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return result;
	}
}
